package com.imooc.mall.filter;

import com.imooc.mall.common.Constant;
import com.imooc.mall.model.pojo.User;
import com.imooc.mall.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 校验管理员
 * 需要实现 javax.servlet; 中的 Filter 接口
 */
public class AdminFilter implements Filter {

    @Autowired
    UserService userService;

    /**
     * 初始化操作
     * @param filterConfig filterConfig
     */
    @Override
    public void init(FilterConfig filterConfig) {

    }

    /**
     * 执行拦截
     * @param servletRequest servletRequest
     * @param servletResponse servletResponse
     * @param filterChain filterChain
     * @throws IOException IOException
     * @throws ServletException ServletException
     */
    @Override
    public void doFilter(
            ServletRequest servletRequest,
            ServletResponse servletResponse,
            FilterChain filterChain
    ) throws IOException, ServletException {
        // 获取 session ，对 servletRequest 进行对象转换，然后获取 session
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpSession session = request.getSession();

        // 判断用户是否登录
        User currentUser = (User) session.getAttribute(Constant.USER_SESSION);
        if (currentUser == null) {
            // 使用 wrapper 进行返回
            PrintWriter out = new HttpServletResponseWrapper((HttpServletResponse) servletResponse).getWriter();
            out.write("{\n" +
                    "    \"status\": 10007,\n" +
                    "    \"msg\": \"NEED_LOGIN\",\n" +
                    "    \"data\": null\n" +
                    "}");
            // 刷行和关闭
            out.flush();
            out.close();
            return;
        }
        // 判断是否是管理员
        if (!userService.checkAdminUser(currentUser)) {
            // 使用 wrapper 进行返回
            PrintWriter out = new HttpServletResponseWrapper((HttpServletResponse) servletResponse).getWriter();
            out.write("{\n" +
                    "    \"status\": 10009,\n" +
                    "    \"msg\": \"IS_ADMIN\",\n" +
                    "    \"data\": null\n" +
                    "}");
            // 刷行和关闭
            out.flush();
            out.close();
        }
        // 校验通过, 进入请求
        filterChain.doFilter(servletRequest, servletResponse);
    }

    /**
     * 拦截完以后操作，相当于 析构方法
     */
    @Override
    public void destroy() {

    }
}
